package omq.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
//import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

//import omq.exception.OmqException;
import omq.api.logger.OMQLogger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class OMQConversions 
{
	static private byte[] Object2ByteArray( Object o ) throws IOException 
	{
		  ByteArrayOutputStream baos = new ByteArrayOutputStream();
		  ObjectOutputStream oos = new ObjectOutputStream( baos );
		  oos.writeObject( o );
		  OMQLogger.getInstance().info("message length = "+baos.toByteArray().length);
		  return baos.toByteArray();
	}
	
	static private Object ByteArray2Object( byte ba[] ) throws IOException, ClassNotFoundException 
    {
		OMQLogger.getInstance().info("message length = "+ba.length);
		ByteArrayInputStream bais = new ByteArrayInputStream( ba );
		ObjectInputStream ois = new ObjectInputStream( bais );
		Object o = ois.readObject();
		return o;
	}
	
	public static String ByteArray2Base64(byte ba[])
	{
		BASE64Encoder encoder = new BASE64Encoder();
		String returnStr = encoder.encode(ba);
		return returnStr;
	}
	
	public static byte[] Base642ByteArray(String base64str) throws IOException
	{
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] ba = decoder.decodeBuffer(base64str);
		return ba;
	}
	
	public static String Object2Base64(Object obj) throws IOException
	{
		return ByteArray2Base64(Object2ByteArray(obj));
	}
	
	public static Object Base642Object(String str) throws IOException, ClassNotFoundException
	{
		return ByteArray2Object(Base642ByteArray(str)); 
	}
}
